<?php
/**
 * @企业类
 * 1、企业列表
 * 2、企业详情
 *
 * */

namespace app\company\controller;

use app\common\controller\HomeCommon;
use app\common\model\Label;
use think\Cache;
use think\Config;

class Index extends HomeCommon
{
    public function __construct()
    {

        parent::__construct();


    }


    /**
     * 获得企业列表
     */
    public function get_company()
    {

        $where = "  a.status=1  ";


        $field = "a.company_name,a.legal,a.com_type,a.logo,a.register_time,a.identification,a.register_money,a.city_str,a.register_money_cg,a.industry_str,p.park_name,a.score_1 as score,a.label,a.chain_name";
        $obj = db('companys a');

        /***关键字*/
        $keywords = request()->param('keywords', '', 'trim');
        if (!empty($keywords)) {
            $where .= " and a.company_name like '%$keywords%' ";
            //查询企业有无数据
            $info = db('companys')->field('id')->where("company_name like '%$keywords%'")->find();
            if (empty($info)) {
                $this->check_list($keywords);
            }
        }
        /***行业*/
        $industry_id = request()->param('industry_id', 0, 'intval');
        if (!empty($industry_id)) {
            $obj = $obj->join('companys_industry b', 'a.id=b.company_id');
            $where .= " and b.status=1 and b.industry_id=$industry_id";
        }

        /***智库机构*/
        $tank_id = request()->param('tank_id', 0, 'intval');
        if (!empty($tank_id)) {
            $obj = $obj->join('tank_organ d', 'a.id=d.com_id');
            $where .= " and d.status=1 ";
        }

        /***产业链*/
        $chain_id = request()->param('chain_id', 0, 'intval');
        if (!empty($chain_id)) {
            $field .= ',d.chain_id ';
            $obj->join('companys_chain d', 'a.id=d.company_id', 'left');
            $where .= " and d.status=1   and d.chain_id=$chain_id";
        }

        /***城市*/
        $city_id = request()->param('city_id', 0, 'intval');
        if (!empty($city_id)) {
            $where .= " and (a.province_id=$city_id or a.city_id=$city_id or a.area_id=$city_id ) ";
        }

        /***排序字段***/
        $sortBy = request()->param('sortBy', 'score_1', 'trim');
        switch ($sortBy) {
            //综合评分
            case 'score_1':
                $obj->order('a.score_1', 'desc');
                break;
            //健康分
            case 'score':
                $obj->order('a.score', 'desc');
                break;
            //投资意向分
            case 'invest_score':
                $obj->order('a.invest_score', 'desc');
                break;
            default:
                exit('未知排序字段');
                break;
        }

        /***企业类型*/
        $top = request()->param('top', '', 'trim');
        if (!empty($top)) {
            switch ($top) {
                //上市
                case 'is_ipo':
                    $where .= " and (a.label like '%上市%' or a.label like '%新三板%' or a.label like '%IPO%' or a.label like '%科创板%' ) ";
                    break;
                //外资
                case 'is_inspect':
                    $obj->where('a.register_money', 'like', '%美元');
                    break;
                //高薪
                case 'is_report':
                    $obj->where('a.label', 'like', '%高新%');
                    break;
                // 融资
                case 'is_market':
                    $obj->where('a.label', 'like', '%轮%');
                    break;
                // top100
                case 'top_100':
                    //todo没做了还
                    break;
                //世界500强
                case 'sj500':
                    $obj->where('a.label', 'like', '%世界500强%');
                    break;
                //中国500强
                case 'zg500':
                    $obj->where('a.label', 'like', '%中国500强%');
                    break;
                default:
                    exit('未知类型');
                    break;
            }
        }

        // 设置分页数据
        $page = request()->param('page', 1, 'intval');
        $limit = request()->param('limit', 15, 'intval');
        Config::set('paginate.page', $page);
        $listobj = $obj->join('parks p', 'a.park_id=p.id', 'LEFT')->field($field)->where($where)->paginate($limit);
        //dd($obj->getLastSql());
        return json(['errcode' => '0', 'msg' => lang('Get success'), 'data' => $listobj]);
    }

    /**
     * 获得企业详情
     **/
    public function get_company_info()
    {
        $where['status'] = ['=', 1];
        $identification = request()->param('identification', '', 'trim');

        if (!empty($identification)) {
            $where['identification'] = ['=', $identification];


            $cache = new Cache();
            $result = $cache->get('company_' . $identification);


            if ($result && 1 == 2) {
                $info = unserialize($result);
            } else {
                $field = "id,identification,elephone,company_name,score,legal,com_type,logo,desc,register_time,register_money,address,lat,lng,city_str as city, invest_score";
                $model = model('Commondata');

                $info = $model->get_detail('companys', $field, $where);

                //工商信息
                $business = db('companys_business')->where(['com_id' => $info['id']])->find();

                //进行三方的工商判断
                if (empty($business)) {
                    $this->check_detail($info['company_name']);
                    $business = db('companys_business')->where(['com_id' => $info['id']])->find();
                }

                //融资情况
                $financing = db('companys_financing')->field('fin_time,fin_round,fin_money,fin_investors')->where(['com_id' => $info['id']])->order('id desc')->select();

                //股东信息
                $holders = db('companys_holders')->field('name,name,money_ratio,money')->where(['com_id' => $info['id']])->order('id desc')->select();

                //对外投资
                $invest = db('companys_invest')->field('in_name,reg_capd,in_money,money_ratio,reg_time,com_state,investment_name')->where(['com_id' => $info['id']])->order('id desc')->select();

                //新闻动态
                $news = db('companys_news a')->join('news b', 'a.news_id=b.id')->field('b.news_name,b.identification,b.create_time')->where(['a.com_id' => $info['id'], 'b.status' => 1])->order('a.id desc')->limit('0,5')->select();

                // 公司产品
                $product = db('companys_products')->where(['com_id' => $info['id'], 'status' => 1])->order('id desc')->select();
                unset($info['id']);
                unset($business['id']);
                unset($business['com_id']);

                $info['business'] = $business;
                $info['financing'] = $financing;
                $info['holders'] = $holders;
                $info['invest'] = $invest;
                $info['news'] = $news;
                $info['product'] = $product;
                $info['city'] = str_replace("'", '"', $info['city']);
                $info['city'] = json_decode($info['city'], true);


                $cache->set('company_' . $identification, serialize($info), 3600);
            }

            return json(['errcode' => '0', 'msg' => lang('Get success'), 'data' => $info]);


        } else {
            return json(['errcode' => '-1', 'msg' => lang('param error'), 'data' => []]);
        }


    }

    /**
     *三方追加list
     */
    private function check_list($keyword)
    {

        if ($keyword) {
            $url = 'http://129.211.44.129:8989/api/list?keyword=' . urlencode($keyword);
            $res = file_get_contents($url);

            $res = json_decode($res, true);

            //p($res);
            if ($res['data']['total'] > 0) {
                foreach ($res['data']['detail'] as $key => $value) {
                    //判断企业是否存在
                    $info = db('companys')->field('id')->where(['company_name' => $value['company']])->find();
                    if (empty($info)) {
                        $info['company_name'] = $value['company'];
                        $info['legal'] = $value['legal_erson'];

                        $info['logo'] = empty($value['logo']) ? "http://wan3.4007283168.com/company_logo/" . rand(1, 10) . ".jpg" : $value['logo'];
                        $info['com_type'] = $value['company_type'];
                        $info['register_money'] = $value['registered_capital'];
                        $info['register_money_cg'] = $value['registered_capital'];
                        $info['score'] = $value['tianyancha_score'];
                        $info['score_1'] = $value['tianyancha_score'];
                        $info['identification'] = uniqid();
                        $info['industry_str'] = '[]';
                        $info['city_str'] = '[]';
                        $result = db('companys')->insert($info);
                        if ($result) {
                            //插入爬虫进程
                            $tem_info = [];
                            $tem_info['com_name'] = $value['company'];
                            $tem_info['register_money_str'] = $value['registered_capital'];
                            $tem_info['com_type'] = $value['company_type'];
                            $tem_info['score'] = $value['tianyancha_score'];
                            db('temporary')->insert($tem_info);
                        }
                    }

                }
            }


        }

    }

    /**
     *三方追加detail
     */
    private function check_detail($company_name)
    {
        if ($company_name) {
            $url = 'http://129.211.44.129:8989/api/detail?company=' . urlencode($company_name);
            $res = file_get_contents($url);

            $res = json_decode($res, true);

            //p($res);
            if ($res['data']) {

                //判断企业是否存在
                $info = db('companys')->field('id,score')->where(['company_name' => $company_name])->find();
                if (!empty($info)) {
                    $base_info = db('companys_business')->field('id')->where(['com_id' => $info['id']])->find();

                    if (empty($base_info)) {
                        $base['reg_cap'] = $res['data']['baseInfo']['regist_money'];
                        $base['reg_cap_unit'] = $res['data']['baseInfo']['shijiao'];
                        $base['reg_time'] = $res['data']['baseInfo']['regist_date'];
                        $base['com_state'] = $res['data']['baseInfo']['com_status'];
                        $base['credit_code'] = $res['data']['baseInfo']['credit_code'];
                        $base['bus_reg_number'] = $res['data']['baseInfo']['regist_money'];
                        $base['tax_number'] = $res['data']['baseInfo']['sw_code'];
                        $base['org_code'] = $res['data']['baseInfo']['org_code'];
                        $base['enter_type'] = $res['data']['baseInfo']['company_type'];
                        $base['industry'] = $res['data']['baseInfo']['industry'];
                        $base['appr_date'] = $res['data']['baseInfo']['check_date'];
                        $base['reg_authority'] = $res['data']['baseInfo']['regist_authority'];
                        $base['bus_start_time'] = $res['data']['baseInfo']['end_date'];
                        $base['tax_qualification'] = $res['data']['baseInfo']['nashui_zizhi'];
                        $base['bus_term'] = $res['data']['baseInfo']['staff_num'];
                        $base['insured_number'] = $res['data']['baseInfo']['canbao_num'];
                        $base['before_name'] = $res['data']['baseInfo']['history_name'];
                        $base['english_name'] = $res['data']['baseInfo']['english_name'];
                        $base['reg_address'] = $res['data']['baseInfo']['address'];
                        $base['scope_of_bus'] = $res['data']['baseInfo']['bussness'];
                        $base['com_id'] = $info['id'];

                        $result = db('companys_business')->insert($base);
                        if ($result) {
                            //更新主企业
                            $info['register_time'] = $base['reg_time'];
                            $info['register_money'] = $base['reg_cap'];
                            $info['register_money_cg'] = $base['reg_cap'];
                            $info['com_type'] = $base['enter_type'];
                            $latlng = $this->get_latlng($base['reg_address']);
                            $industry = $this->get_industry($base['industry']);
                            $score = $this->get_score($res['data']['data']);
                            $city = $this->get_city($res['data']['baseInfo']['province'], $res['data']['baseInfo']['city'], $res['data']['baseInfo']['area']);
                            $info['lat'] = $latlng['lat'];
                            $info['lng'] = $latlng['lng'];

                            $info['province_id'] = $city['province_id'];
                            $info['city_id'] = $city['city_id'];
                            $info['area_id'] = $city['area_id'];
                            $info['invest_score'] = $score;
                            $info['address'] = $base['reg_address'];
                            //p($info);
                            if ($info['score']) {
                                $info['score_1'] = ($score + $info['invest_score']) / 2;
                            } else {
                                $info['score_1'] = $score;
                            }

                            db('companys')->update($info);


                            if ($industry['code'] == 1) {
                                foreach ($industry['data'] as $key => $value) {
                                    # code...
                                    $indu = db('companys_industry')->where(['company_id' => $info['id'], 'industry_id' => $value])->find();
                                    if (empty($indu)) {
                                        $indu['company_id'] = $info['id'];
                                        $indu['industry_id'] = $value;
                                        db('companys_industry')->insert($indu);

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    /*
    *获取分数
    */
    private function get_score($data)
    {
        $score = 0;


        ///注册资金3000以上 8  1000-3000 5  200-1000 4  200以下  3 
        if (!empty($data['zczj'])) {
            if (preg_match('/\d+/', $data['zczj'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 3000) {
                    $score += 8;
                } elseif ($content * 1 < 3000 && $content * 1 >= 1000) {
                    $score += 5;
                } elseif ($content * 1 < 1000 && $content * 1 >= 500) {
                    $score += 4;
                } else {
                    $score += 3;
                }
            } else {
                $score += 3;
            }
        } else {
            $score += 3;
        }
        //#社保人数   50以上5  10-50 4   1-10 3   无2
        if (!empty($data['sbrs'])) {
            if (preg_match('/\d+/', $data['sbrs'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 50) {
                    $score += 5;
                } elseif ($content * 1 < 50 && $content * 1 >= 10) {
                    $score += 4;
                } elseif ($content * 1 < 10 && $content * 1 >= 1) {
                    $score += 3;
                } else {
                    $score += 2;
                }
            } else {
                $score += 2;
            }
        } else {
            $score += 2;
        }
        //#对外投资有 4  无2 分 
        if (!empty($data['dwtzs'])) {
            $score += 4;
        } else {
            $score += 2;
        }

        //融资历程3以上15  1-3 10   1 6   无3
        if (!empty($data['rzlcs'])) {
            if (preg_match('/\d+/', $data['rzlcs'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 3) {
                    $score += 15;
                } elseif ($content * 1 < 3 && $content * 1 > 1) {
                    $score += 10;
                } elseif ($content * 1 == 1) {
                    $score += 6;
                } else {
                    $score += 3;
                }
            } else {
                $score += 3;
            }
        } else {
            $score += 3;
        }
        //#分支机构3以上5  1-3 3   无3
        if (!empty($data['fzjgs'])) {
            if (preg_match('/\d+/', $data['fzjgs'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 3) {
                    $score += 5;
                } elseif ($content * 1 < 3 && $content * 1 >= 1) {
                    $score += 3;
                } else {
                    $score += 3;
                }
            } else {
                $score += 3;
            }
        } else {
            $score += 3;
        }

        //招聘信息 3个月有 10  无7 
        if (!empty($data['zpDate'])) {
            $score += 10;
        } else {
            $score += 7;
        }

        //#资质证书有多个 5  1-5  3分  无 0 
        if (!empty($data['zzzhsj'])) {
            if (preg_match('/\d+/', $data['zzzhsj'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 5) {
                    $score += 5;
                } elseif ($content * 1 < 5 && $content * 1 >= 1) {
                    $score += 3;
                } else {
                    $score += 0;
                }
            } else {
                $score += 0;
            }
        } else {
            $score += 0;
        }

        //#商标信息多个 多个5   1个3分  无1 
        if (!empty($data['sbxxs'])) {
            if (preg_match('/\d+/', $data['sbxxs'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 5) {
                    $score += 5;
                } elseif ($content * 1 < 5 && $content * 1 >= 1) {
                    $score += 3;
                } else {
                    $score += 1;
                }
            } else {
                $score += 1;
            }
        } else {
            $score += 1;
        }
        //#专利信息多个 多个5   1个3分  无1 
        if (!empty($data['zlxxs'])) {
            if (preg_match('/\d+/', $data['zlxxs'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 5) {
                    $score += 5;
                } elseif ($content * 1 < 5 && $content * 1 >= 1) {
                    $score += 3;
                } else {
                    $score += 1;
                }
            } else {
                $score += 1;
            }
        } else {
            $score += 1;
        }

        //#软著信息多个 多个5   1个3分  无1 
        if (!empty($data['rzlcs'])) {
            if (preg_match('/\d+/', $data['rzlcs'], $arr)) {
                $content = $arr[0];

                if ($content * 1 >= 5) {
                    $score += 5;
                } elseif ($content * 1 < 5 && $content * 1 >= 1) {
                    $score += 3;
                } else {
                    $score += 1;
                }
            } else {
                $score += 1;
            }
        } else {
            $score += 1;
        }
        //#上市公司（含新三板）和高新13  上非高10  高非上8   其他5
        $shangflag = 0;
        $gaoflag = 0;
        if (!empty($data['label'])) {
            if (strstr($data['label'], '上市') || strstr($data['label'], '新三板') || strstr($data['label'], '创业板')) {
                $shangflag = 1;
            }
            if (strstr($data['label'], '高新')) {
                $gaoflag = 0;
            }
        }
        if ($shangflag && $gaoflag) {
            $score += 13;
        } elseif ($shangflag && !$gaoflag) {
            $score += 10;
        } elseif (!$shangflag && $gaoflag) {
            $score += 8;
        } else {
            $score += 5;
        }
        //#所属行业见表
        if (!empty($data['hy'])) {
            $res = db('temporary_industry')->where(['name' => $data['hy']])->find();
            if ($res) {
                $score += $res['score'] * 2;
            } else {
                $score += 4;
            }
        } else {
            $score += 4;
        }
        //经营范围
        $num = 0;
        if (!empty($data['jyfw'])) {
            if (strstr($data['jyfw'], '研发')) {
                $num++;
            }
            if (strstr($data['jyfw'], '生产')) {
                $num++;
            }
            if (strstr($data['jyfw'], '封装')) {
                $num++;
            }
            if (strstr($data['jyfw'], '设计')) {
                $num++;
            }
            if (strstr($data['jyfw'], '制造')) {
                $num++;
            }
            if (strstr($data['jyfw'], '智能')) {
                $num++;
            }
            if (strstr($data['jyfw'], '算法')) {
                $num++;
            }
            if (strstr($data['jyfw'], '生物')) {
                $num++;
            }
            if (strstr($data['jyfw'], '芯片')) {
                $num++;
            }
            if (strstr($data['jyfw'], '新能源')) {
                $num++;
            }
            if (strstr($data['jyfw'], '开发')) {
                $num++;
            }
        }
        if ($num >= 3) {
            $score += 10;
        } elseif ($num < 3 && $num >= 1) {
            $score += 5;
        } else {
            $score += 2;
        }


        return $score;
    }

    /*
    *获取经纬度
    */
    private function get_latlng($address)
    {
        if ($address) {
            $url = "http://api.map.baidu.com/geocoding/v3/?address=$address&output=json&ak=qKFBUW1sFEDzBHnbvqI0whctefZjdx5i";
            $res = file_get_contents($url);


            $res = json_decode($res, true);

            if ($res['status'] == 0) {
                $lat = $res['result']['location']['lat'];
                $lng = $res['result']['location']['lng'];
                $result = ['lat' => $lat, 'lng' => $lng];
            } else {
                $result = ['lat' => 0, 'lng' => 0];
            }
        } else {
            $result = ['lat' => 0, 'lng' => 0];
        }
        return $result;
    }

    /*
    *获取行业
    */
    public function get_industry($industry)
    {
        if ($industry) {
            $res = db('industry')->where(['industry_name' => $industry])->find();
            if ($res && $res['pid']) {
                $res_1 = db('industry')->where(['id' => $res['pid']])->find();
                if ($res_1) {
                    $result = ['code' => 1, 'data' => [$res['id'], $res_1['id']]];
                } else {
                    $result = ['code' => 1, 'data' => [$res['id']]];
                }
            } else {
                $result = ['code' => 0, 'data' => []];
            }
        } else {
            $result = ['code' => 0, 'data' => []];
        }
        return $result;

    }

    /*
    *获取行业
    */
    public function get_city($province, $city, $area)
    {

        $province_id = 0;
        $city_id = 0;
        $area_id = 0;
        if ($province) {
            $res = db('city')->where("city_name like '%$province%' and type=1 ")->find();

            if ($res) {
                $province_id = $res['id'];
            }
        }
        if ($city) {
            $res = db('city')->where("city_name like '%$city%' and type=2 ")->find();
            if ($res) {
                $city_id = $res['id'];
            }
        }
        if ($area) {
            $res = db('city')->where("city_name like '%$area%' and type=3 ")->find();
            if ($res) {
                $area_id = $res['id'];
            }
        }
        return ['province_id' => $province_id, 'city_id' => $city_id, 'area_id' => $city_id];
    }


}
